/**
 * @author kan
 */

if (!window['console']){
    window.console = {
        info: function(){},
        log: function(){},
        warn: function(){},
        error: function(){},
        debug: function(){}
    };
}

String.prototype.ucfirst = function() {
    if (this.length == 0) {
        return this;
    }

    return this.charAt(0).toUpperCase() + this.substring(1);
}

String.prototype.trim = function() {
    return this.replace(/^\s+.*\s+$/, "");
}

function simpleSprintf() {
    var template = arguments[0];
    var parts = template.split("\%\s");
    var defaultArgument = arguments[1];
    var ret = parts[0];
    for (var i = 1; i < parts.length; i++) {
        if (arguments[i] != undefined && arguments[i] != null) {
            ret += arguments[i];
        } else {
            ret += defaultArgument;
        }
       ret += parts[i];
    }

    return ret;
}

function ajaxPost(jqueryElement){
    jqueryElement.ajaxStart(function(){
        this.disabled = true;
        $.blockUI();
    }).ajaxStop(function(){
        $.unblockUI();
        this.disabled = false;
    });
    var args = $.makeArray(arguments);
    args.shift();
    $.post.apply(jqueryElement, args);
}

function ucFirst(str){
    return str.substr(0, 1).toUpperCase() + str.substr(1);
}

function showErrorDialog(msg){
    $("#error-dialog-msg").html(msg);
    $("#error-dialog").dialog({
        modal: true,
        resizable: false
    });

    $("#error-dialog .ui-dialog-titlebar a").remove();
}

function createGrid(name, colNames, colModels){
    jsName = name.replace("-", "_");

    $("#" + name + "-table").jqGrid({
        url: jsName + '.json',
        datatype: "json",
        colNames: colNames,
        colModel: colModels,
        rowNum: 10,
        rowList: [10, 20, 30],
        pager: "#" + name + "-pager",
        sortname: "name",
        viewrecords: true,
        sortorder: "desc",
        loadonce: true,
        caption: ""
    });

    return $("#" + name + "-table").jqGrid("navGrid", "#" + name + "-pager", {
        edit: false,
        add: false,
        del: false
    });
}

function getJSON(url){
    var json = {};
    $.ajax({
        async: false,
        url: url,
        dataType: "json",
        data: {
            rows: 10
        },
        success: function(data){
            json = data;
        }
    });
    return json;
}

function createSelectOptions(id, array) {
    var html = "";
    $.each(array, function() {
        html += simpleSprintf("<option value='%s'>%s</option>", this, this);
    });
    
    return $("#" + id).html(html);
}

